<style lang="scss" scoped src="./update.scss"></style>
<template>
    <page-box>
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
                <ask-breadcrumb-item>{{$route.query.id ? "编辑" : "新增"}}</ask-breadcrumb-item>
            </ask-breadcrumb>
        </template>
        <div class="regional-edit-container">
            <el-steps class="regional-update-steps" :active="activeStep">
                <el-step title="开通区域" icon="el-icon-refresh"></el-step>
                <el-step title="创建账号" icon="el-icon-user"></el-step>
            </el-steps>
            <template v-if="activeStep === 1">
                <el-form ref="updateForm" label-position="right" :model="updateForm" :rules="updateFormRules" class="updateForm">
                    <el-form-item :label="isArea ? '区域' : '镇域'" prop="cityCode" class="city-form">
                        <ask-city-cascader
                            :cityQuery="_isOperation ? 'notAuth': 'authArea'"
                            v-if="!$route.query.id"
                            ref="cityCascader"
                            v-model="updateForm.cityCode"
                            @change="handleChange"
                            :showModel="showModel"
                            clear />
                        <span v-else>{{updateForm.governmentName}}</span>
                    </el-form-item>
                    <el-form-item label="开通时间" prop="timeRange" class="city-form">
                        <el-date-picker
                            v-model="updateForm.timeRange"
                            type="datetimerange"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :default-time="['00:00:00', '23:59:59']">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="到期提醒设置" prop="remind" class="remind-form">
                        <el-form-item prop="remindTime" class="remind-form-item">
                            <span class="label">到期前</span>
                            <el-input placeholder="请输入内容" v-model="updateForm.remindTime"></el-input>
                            <el-select v-model="updateForm.remindTimeUnit">
                                <el-option label="天" :value="1"></el-option>
                                <el-option label="周" :value="2"></el-option>
                                <el-option label="月" :value="3"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="" prop="remindFrequency" class="remind-form-item">
                            <span class="label">每隔</span>
                            <el-input placeholder="请输入内容" v-model="updateForm.remindFrequency"></el-input>
                            <el-select v-model="updateForm.remindFrequencyUnit">
                                <el-option label="小时" :value="0"></el-option>
                                <el-option label="天" :value="1"></el-option>
                                <el-option label="周" :value="2"></el-option>
                            </el-select>
                            <span style="margin-left: 10px">提醒一次</span>
                        </el-form-item>
                        <p class="tips">
                            默认提示消息为"(区域)+您的管理系统于+(到期时间)+即将到期，请及时联系运营人员办理续期+(区域运营电话1，区域运营电话2)"
                        </p>
                        <el-checkbox-group v-model="updateForm.type" :min="1">
                            <el-checkbox label="1">短信提醒</el-checkbox>
                            <el-checkbox label="2">系统消息提醒</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="开通子级账户数量" prop="childNumber" class="city-form">
                        <div class="childNumber-form">
                            <el-input-number v-model="updateForm.childNumber" controls-position="right" :min="1" :max="isArea ? maxChildNumber : 99999" class="childNumber-input" placeholder="请输入开通子级账户数量"></el-input-number>
                            <transition name="page-transition-slide-in-right">
                                <span v-if="isArea && updateForm.cityCode">该区域下共{{maxChildNumber}}个乡镇</span>
                            </transition>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <div class="btn-box">
                            <el-button @click="toRegionalTable">取消</el-button>
                            <el-button type="primary" @click="toNext('updateForm')">下一步</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </template>
            <template v-else>
                <el-form ref="updateForm" label-position="right" :model="updateForm" :rules="updateFormRules" class="updateForm-steps2" label-width="120px">
                    <el-form-item :label="isArea ? '区域超管账号' : '镇域超管账号'" prop="account">
                        <el-input v-model="updateForm.account" class="updateForm-steps2-input" placeholder="请设置登陆账号"></el-input>
                    </el-form-item>
                    <el-form-item :label="isArea ? '区域超管密码' : '镇域超管密码'" prop="remind">
                        <el-form-item prop="password" v-if="updateType === 'add'">
                            <el-input v-model="updateForm.password" class="updateForm-steps2-input" placeholder="请设置6~12位数字字母组合新密码"></el-input>
                        </el-form-item>
                        <template v-else>
                            <el-popover
                                placement="bottom"
                                width="300"
                                @show="showPop"
                                @after-leave="afterLeave"
                                trigger="click"
                                v-model="visiblePassword">
                                <el-form-item prop="newPassword" v-if="visiblePassword">
                                    <div class="pop-box">
                                        <el-input v-model="updateForm.newPassword" class="updateForm-steps2-input" placeholder="请输入新密码" size="small"></el-input>
                                        <el-button @click="savePassword" size="small">确认</el-button>
                                    </div>
                                </el-form-item>
                                <el-button type="text" slot="reference" :class="{reset: updateForm.password}">
                                    {{updateForm.password ? "重置成功" : "重置密码"}}<i v-if="updateForm.password" class="el-icon-check"></i>
                                </el-button>
                            </el-popover>
                            <p class="tips">如密码无需修改可直接在下方点击完成</p>
                        </template>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="activeStep = 1">上一步</el-button>
                        <el-button type="primary" @click="toFinish('updateForm')">完成</el-button>
                    </el-form-item>
                </el-form>
            </template>
        </div>
    </page-box>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { checkPassword } from "@/utils/vee-validate";
import { State } from "vuex-class";
const customCheckPassword = (rule: any, value: any, callback: any) => {
    if (rule.field === "newPassword" && !value) {
        callback();
    } else if (!checkPassword(value)) {
        callback(new Error('请设置6~12位数字字母组合新密码'));
    } else {
        callback();
    }
};

const checkTel = (rule: any, value: any, callback: any) => {
    if (!(/^[0-9a-zA-Z]*$/g.test(value))) {
        callback(new Error('请输入英文和数字'));
    } else {
        callback();
    }
};

@Component({
    name: "RegionalEditNotAlive"
})

export default class RegionalEdit extends Vue {
    @State(state => state.authArea) authArea: any;
    // 当前用户所处层级菜单
    get client() {
        return this.$getUserLevel(this.authArea && this.authArea.orgCategoryId).name;
    }

    get _isOperation() {
        return ['ADMIN', 'OPERATION_ADMIN', 'OPERATION'].includes(this.client);
    }

    // 新增/编辑
    updateType = "add"
    // 步骤条
    activeStep = 1
    // 选中的区域信息
    areaValue = {}
    // 表单
    updateForm: any = {
        governmentId: "",
        governmentName: "",
        // cityCode
        cityCode: "",
        // 开通时间范围
        timeRange: [],
        // 到期前提醒
        remindTime: "1",
        // 提醒前单位
        remindTimeUnit: 1,
        // 提醒频率
        remindFrequency: "1",
        // 频率单位
        remindFrequencyUnit: 0,
        // 发送消息方式
        type: ["1", "2"],
        // 子账号数量
        childNumber: "",
        // 超管账号
        account: "",
        // 超管密码
        password: "",
        newPassword: ""
    }

    // 是区域
    isArea = true

    // 最大子级数量
    maxChildNumber = 1

    // 区域显示内容
    showModel: string[] = ['province', 'city', 'area'] // 'town', 'village'

    // 修改密码显示
    visiblePassword = false

    updateFormRules = {
        cityCode: [
            { required: true, message: '请选择区域', trigger: 'change' }
        ],
        timeRange: [
            { required: true, message: '请选择开通时间', trigger: 'blur' }
        ],
        remind: [
            { required: true, validator: (rule: any, value: any, callback: any) => { callback(); } }
        ],
        remindTime: [
            { required: true, message: '请输入到期提醒时间', trigger: 'blur' }
        ],
        remindFrequency: [
            { required: true, message: '请输入提醒频率', trigger: 'blur' }
        ],
        childNumber: [
            { required: true, message: '请输入开通子级账户数量', trigger: 'blur' }
        ],
        account: [
            { required: true, message: '请设置登陆账号', trigger: 'change' },
            { validator: checkTel, trigger: 'change' }
        ],
        password: [
            { required: true, validator: customCheckPassword, trigger: 'change' }
        ],
        newPassword: [
            { required: true, validator: customCheckPassword, trigger: 'change' }
        ]
    }

    get getMenuName() {
        const _name = this.$route.name;
        if (_name === "RegionalUpdate") {
            return "MenuAreaManage";
        } else {
            return "MenuAreaManage";
        }
    }

    created() {
        this.initPage();
    }

    initPage() {
        this.updateType = this.$route.query.id ? "edit" : "add";
        if (this.updateType === "add") {
            const today = new Date();
            const year = today.getFullYear() + 1;
            const month = today.getMonth() + 1;
            const day = today.getDate();
            today.setTime(today.getTime() + 24 * 60 * 60 * 1000);
            this.updateForm.timeRange = [
                `${today.getFullYear()}-${(today.getMonth() + 1)}-${today.getDate()} 00:00:00`,
                `${year.toString()}-${month}-${day} 23:59:59`
            ];
        } else {
            this.initData();
        }
        if (this.$route.name === "RegionalUpdateOperateTown") {
            this.isArea = false;
            this.showModel.push("town");
        }
    }

    // 初始化编辑内容
    initData() {
        this.$server["regional/getAccountInfo"]({
            data: {
                userId: this.$route.query.id
            }
        }).then(async(res: any) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                this.updateForm = {
                    governmentId: data.governmentId,
                    governmentName: data.governmentName,
                    // cityCode
                    cityCode: data.cityCode || "",
                    // 开通时间范围
                    timeRange: [data.startTime, data.endTime],
                    // 到期前提醒
                    remindTime: data.remindExpiredTime,
                    // 提醒前单位
                    remindTimeUnit: data.remindExpiredUnit,
                    // 提醒频率
                    remindFrequency: data.remindFrequencyTime,
                    // 频率单位
                    remindFrequencyUnit: data.remindFrequencyUnit,
                    // 发送消息方式
                    type: data.remindWay.split(","),
                    // 超管账号
                    account: data.username,
                    // 超管密码
                    password: "",
                    newPassword: ""
                };
                await this.getChildNumber();
                // 子账号数量
                this.updateForm.childNumber = data.licensorNum;
            } else {
                this.$message.error(res.data.message);
            }
        });
    }

    // 修改区域选择
    handleChange(val: any) {
        this.areaValue = val;
        if (!this.updateForm.cityCode) return false;
        if (val.province.code) {
            (this.$refs.updateForm as any).validateField("cityCode");
            this.getChildNumber();
        }
    }

    // 获取区域子级数量
    async getChildNumber() {
        const res: any = await this.$server.cityQuery({
            loader: false,
            data: {
                code: this.updateForm.cityCode
            }
        });
        if (res.data.code === 200) {
            this.maxChildNumber = res.data.data.length;
        }
    }

    // 下一步
    toNext(formName: string) {
        (this.$refs[formName] as any).validate((valid: any) => {
            if (valid) {
                if (!this.$route.query.id) {
                    this.updateForm.governmentId = this.getAreaId();
                }
                this.activeStep = 2;
            }
        });
    }

    // 取消编辑
    toRegionalTable() {
        this.$router.go(-1);
    }

    // 保存密码
    savePassword() {
        (this.$refs.updateForm as any).validateField("newPassword", (valid: any) => {
            if (!valid) {
                this.updateForm.password = this.updateForm.newPassword;
                this.visiblePassword = false;
            }
        });
    }

    // 关闭重置密码弹窗
    afterLeave() {
        this.updateForm.newPassword = "";
    }

    // 打开修改密码弹窗
    showPop() {
        this.updateForm.newPassword = this.updateForm.password;
    }

    // 完成
    toFinish(formName: string) {
        (this.$refs[formName] as any).validate((valid: any) => {
            if (valid) {
                const {
                    timeRange,
                    remindTime,
                    remindTimeUnit,
                    remindFrequency,
                    remindFrequencyUnit,
                    type,
                    childNumber,
                    account,
                    password,
                    governmentId
                } = this.updateForm;
                this.$server["regional/updateOperate"]({
                    data: {
                        username: account,
                        password,
                        endTime: timeRange[1],
                        governmentId: governmentId,
                        licensorNum: childNumber,
                        orgCategoryId: this.isArea ? this.$USER_LEVEL.REGIONAL_ADMIN.value : this.$USER_LEVEL.TOWN_ADMIN.value,
                        remindExpiredTime: remindTime,
                        remindExpiredUnit: remindTimeUnit,
                        remindFrequencyTime: remindFrequency,
                        remindFrequencyUnit: remindFrequencyUnit,
                        remindWay: type.join(","),
                        startTime: timeRange[0],
                        userId: this.$route.query.id || ""
                    }
                }).then((res: any) => {
                    if (res.data.code === 200) {
                        if (this.$route.query.id && password) {
                            this.toChangePassword(password);
                        } else {
                            this.$message({
                                type: 'success',
                                message: `${this.isArea ? '区域' : '镇域'}超管账号${this.$route.query.id ? '已修改' : '开通成功'}!`
                            });
                            this.$router.push({ path: this.isArea ? '/system-manage/area' : '/system-manage/town' });
                        }
                    } else {
                        this.$message.error(res.data.message);
                    }
                });
            }
        });
    }

    // 修改密码
    toChangePassword(password: any) {
        this.$server["regional/updatePassword"]({
            data: {
                password,
                id: this.$route.query.id || ""
            }
        }).then((res: any) => {
            if (res.data.code === 200) {
                this.$message({
                    type: 'success',
                    message: `${this.isArea ? '区域' : '镇域'}超管账号${this.$route.query.id ? '已修改' : '开通成功'}!`
                });
                this.$router.push({ path: this.isArea ? '/system-manage/area' : '/system-manage/town' });
            } else {
                this.$message.error(res.data.message);
            }
        });
    }

    // 查询政级id
    getAreaId() {
        let name = "";
        for (let i = this.showModel.length - 1; i >= 0; i--) {
            if (this.areaValue[this.showModel[i]].name === "") {
                continue;
            } else {
                name = `askCity${this.showModel[i]}PanelRef`;
                break;
            }
        }
        const list = (this.$refs.cityCascader as any).$refs[name][0].sourceList;
        return list.filter((item: any) => item.code.toString() === this.updateForm.cityCode)[0].id;
    }
}
</script>

